package cn.edu.sdjzu.xg.eagle.controller;

import cn.edu.sdjzu.xg.eagle.entity.User;
import cn.edu.sdjzu.xg.eagle.factory.ServiceFactory;
import cn.edu.sdjzu.xg.eagle.service.UserServiceImpl;
import cn.edu.sdjzu.xg.eagle.util.JSONUtil;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.SQLException;

@WebServlet("/loginController")
public class LoginController extends HttpServlet {
    //登录

//    {
//        "username":"张烁瑜",
//            "password":"123456"
//    }


//    pm.test('login OK', function () {
//        var jsonData = pm.response.json();
//        pm.expect(jsonData.message).to.eql("操作成功");
//        pm.expect(jsonData.code).to.eql("200");
//    });


//    pm.test('login OK', function () {
//        var jsonData = pm.response.json();
//        pm.expect(jsonData.message).to.eql("操作成功");
//        pm.expect(jsonData.code).to.eql("200");
//        if(jsonData.token){
//            pm.expect(jsonData.token.length).to.be.above(20);
//        }
//    });


    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("application/json;charset=UTF-8");
        String user_json = JSONUtil.getJSON(req);
        User userToLogin = JSON.parseObject(user_json,User.class);
        JSONObject message = new JSONObject();
        try{
            ServiceFactory.getService(UserServiceImpl.class,"UserServiceImpl").login(userToLogin);
            if (userToLogin.getId() == null){
                message.put("message","用户不存在/密码错误");
                message.put("code","500");
                resp.getWriter().println(JSON.toJSONString(message));
            }else {
                message.put("message","操作成功");
                message.put("code","200");
                resp.getWriter().println(JSON.toJSONString(message));
            }
        }catch (SQLException e){
            message.put("message","数据库操作异常");
            resp.getWriter().println(JSON.toJSONString(message));
            e.printStackTrace();
        }catch (Exception e){
            message.put("message","网络异常");
            resp.getWriter().println(JSON.toJSONString(message));
            e.printStackTrace();
        }
    }
}
